#coding=utf-8
from django import forms
from choices import CONDITION_TYPES
from models import Rule, AttachmentCondition, \
    DateCondition, AddressCondition, KeywordCondition, \
    ANrCondition, SizeCondition, ResentCondition
import re

#===============================================================================
# ### rule ###
#===============================================================================
    
class RuleForm (forms.ModelForm):
    '''Rule form model'''
    
    class Meta:
        model = Rule
        exclude = ('is_tmp', 'conditions')

    def proper_expression(self):
        model = self.save(commit=False)
        conds_nr = model.conditions.count()
        
        if conds_nr > 0:
            txt = ""
            for i in range(conds_nr):
                if i == 0:
                    txt = str(i+1)
                else:
                    txt = txt + " & " + str(i+1)
            return txt
        
    def __init__(self, conds_nr, *args, **kwarg):
        super(RuleForm, self).__init__(*args, **kwarg)
        if int(conds_nr) > 0:
            self.fields['expression'].widget.attrs['value']=self.proper_expression()
        
    def clean(self):
        cleaned_data = super(RuleForm, self).clean()
        expression = cleaned_data.get("expression")
        
        if expression:
            model = self.save(commit=False)
            conds_nr = model.conditions.count()
            
            err_str = u"Niepoprawne wyrażenie!"
            if int(conds_nr) == 0:
                self._errors["expression"] = self.error_class([err_str])
                del cleaned_data['expression']
                return cleaned_data
            
            regex = re.compile('[0-' + str(conds_nr) + '&|~ ]+')
            text = self.cleaned_data['expression']
            result = regex.match(text)
    
            if result is None or result.group().count != text.count:
                self._errors["expression"] = self.error_class([err_str])
                del cleaned_data['expression']
        
        return cleaned_data
        
#===============================================================================
# ### new condition ###
#===============================================================================

class NewConditionForm(forms.Form):
    '''New condition form model'''
    
    condition_types = forms.ChoiceField(label='', choices=CONDITION_TYPES)
    
#===============================================================================
# ### attachment condition ###
#===============================================================================

class AttachmentConditionForm(forms.ModelForm):
    
    class Meta:
        model = AttachmentCondition
        exclude = ('condition',)

#===============================================================================
# ### date condition ###
#===============================================================================

class DateConditionForm(forms.ModelForm):
    
    period = forms.ChoiceField(choices = ((1, 'dniu'), 
                                          (2, 'dniach'), 
                                          ))
    period.widget.attrs["onchange"]="changePeriod();" 
    
    class Meta:
        model = DateCondition
        exclude = ('condition',)
        
    def clean(self):
        cleaned_data = super(DateConditionForm, self).clean()
        period = cleaned_data.get("period")
        to = cleaned_data.get("to_d")

        if period == "2" and to is None:
            self._errors["to_d"] = self.error_class([u"To pole jest wymagane!"])
            del cleaned_data["to_d"]
        
        return cleaned_data
            
#===============================================================================
# ### address condition ###
#===============================================================================

class FromConditionForm(forms.ModelForm):
    
    class Meta:
        model = AddressCondition
        exclude = ('condition', 'type')

class ToConditionForm(forms.ModelForm):
    
    class Meta:
        model = AddressCondition
        exclude = ('condition', 'type')

#===============================================================================
# ### keyword condition ###
#===============================================================================

class KeywordConditionForm(forms.ModelForm):
    
    class Meta:
        model = KeywordCondition
        exclude = ('condition',)

#===============================================================================
# ### attachment nr condition ###
#===============================================================================

class ANrConditionForm(forms.ModelForm):
    
    class Meta:
        model = ANrCondition
        exclude = ('condition',)

#===============================================================================
# ### msg size condition ###
#===============================================================================

class SizeConditionForm(forms.ModelForm):
    
    class Meta:
        model = SizeCondition
        exclude = ('condition',)

#===============================================================================
# ### resent condition ###
#===============================================================================

class ResentConditionForm(forms.ModelForm):
    
    class Meta:
        model = ResentCondition
        exclude = ('condition',)

#===============================================================================
# ### subject condition ###
#===============================================================================

class SubjectConditionForm(forms.ModelForm):
    
    class Meta:
        model = KeywordCondition
        exclude = ('condition', 'keyword_range', 'how_many_operator', 'how_many')
        